from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from goods.models import SPU,Brand,GoodsCategory
from meiduo_admin.serializers import spu_serializers
from rest_framework.response import Response
from django.conf import settings
from fdfs_client.client import Fdfs_client
from meiduo_mall.utils.fdfs.MyFileStorage import MyStorage

#1,操作spu
class SPUView(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = spu_serializers.SPUSerializer
    queryset = SPU.objects.all()

    #1,获取品牌
    def brand(self,request):
        #1,查询所有的品牌
        brands = Brand.objects.all()

        #2,获取序列化器
        serializer = spu_serializers.BrandSerializer(instance=brands,many=True)

        #3,返回响应
        return Response(serializer.data)

    #2,一级分类
    def category(self,request):
        #1,查询一级分类
        categories1 = GoodsCategory.objects.filter(parent__id=None)

        #2,获取序列化器
        serializer = spu_serializers.CategorySerializer(instance=categories1,many=True)

        #3,返回响应
        return Response(serializer.data)

    #3,二级,三级分类
    def category_sub(self,request,pk):
        #1,获取二级,三级分类
        categories = GoodsCategory.objects.filter(parent__id=pk)

        #2,获取序列化器
        serializer = spu_serializers.CategorySerializer(instance=categories,many=True)

        #3,返回响应
        return Response(serializer.data)

    #4,上传图片
    def upload_image(self,request):
        #1,获取参数
        image = request.FILES.get("image")

        #2,上传图片,判断是否上传成功
        image_url = MyStorage().save(None,image)
        if not image_url:
            return Response({"errmsg":"上传失败"},status=400)

        #3,返回响应
        return Response({
            "img_url":settings.BASE_URL + image_url
        })